import { Component, OnInit } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { Title } from '@angular/platform-browser';

import { Login } from './login';
import { AuthService } from '../shared/auth.service';

import 'material-design-lite';

@Component({
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  public model = new Login('admin', '123456');

  constructor(
    private authService: AuthService,
    private router: Router,
    private titleService: Title
  ) { }

  public ngOnInit() {
    this.titleService.setTitle('登录');
    this.setMessage();
  }

  public setMessage() {
    this.model.message = this.authService.isLoggedIn ? '已登录' : '已登出';
  }

  public login() {
    this.model.message = '正在登录中...';
    this.authService.login().subscribe(() => {
      this.setMessage();
      if (this.authService.isLoggedIn) {
        // 获取重定向URL
        const redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/dock';

        const navigationExtras: NavigationExtras = {
          queryParamsHandling: 'preserve',
          preserveFragment: true
        };
        this.router.navigate([redirect], navigationExtras);
      }
    });
  }

}
